#!/usr/bin/env ruby
require 'optparse'

@vendors = {
  'rubygems': 'https://rubygems.org/',
  'ruby-china': 'https://gems.ruby-china.com/',
  'tuna': 'https://mirrors.tuna.tsinghua.edu.cn/rubygems/'
}

ARGV.push('--help') if ARGV.empty?
begin
  OptionParser.new do |opts|
    opts.banner = <<~EOF
      切换 Ruby gems 源，可用的提供商包括：

      #{
        @vendors.keys.join("\n")
      }
    EOF
  end.parse!
rescue OptionParser::ParseError => ex
  STDERR.puts ex.message
  exit 1
end

def remove_sources
  lines = `gem sources`.split("\n")
  sources = lines[2..-1] || []
  sources.each do |source|
    system "gem sources --remove #{source}"
  end
end

def add_source(vendor)
  system "gem sources --add #{@vendors[vendor]}"
end

vendor = ARGV[0].to_sym
unless @vendors.key?(vendor)
  STDERR.puts "不支持的提供商：#{vendor}"
  exit
end

remove_sources
add_source(vendor)

puts "已经将 gems 的源设置为 #{vendor} 提供的镜像，可以调用 `gem sources` 命令检查。"
